<template>
    <div>
        <h4>商家详情</h4>
        <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="1">
                <el-form ref="myForm" :model="myForm" label-width="80px" class="form-group" :rules="rules">
                    <el-form-item label="店铺名称" prop="name">
                        <el-input v-model="myForm.name" placeholder="请输入名称"></el-input>
                    </el-form-item>
                    <el-form-item label="店铺地址" prop="address">
                        <el-input v-model="myForm.address" placeholder="请输入地址"></el-input>
                    </el-form-item>
                    <el-form-item label="店铺logo" prop="logo" title="商家logo">
                        <el-upload
                                class="logo-upload"
                                :action="upload_action"
                                :show-file-list="false"
                                :on-success="onUploadSuccess"
                                :before-upload="onBeforeUpload"
                        >
                            <img alt="" v-if="myForm.logo" :src="myForm.logo" class="logo"/>
                            <i v-else class="el-icon-plus logo-upload-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="店铺经度" prop="lon">
                        <el-input v-model="myForm.lon" placeholder="请输入经度"></el-input>
                    </el-form-item>
                    <el-form-item label="店铺纬度" prop="lat">
                        <el-input v-model="myForm.lat" placeholder="请输入纬度"></el-input>
                    </el-form-item>
                    <el-form-item label="店铺公告" prop="notice">
                        <el-input v-model="myForm.notice" placeholder="请输入公告"></el-input>
                    </el-form-item>
                    <el-form-item label="起送价格" prop="up_send">
                        <el-input v-model="myForm.up_send" placeholder="请输入起送价"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click.prevent="onSubmit">提交</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="商品管理" name="2">
                <ul class="category-list">
                    <li class="category-group" v-for="(category, index) in categories" :key="category.id+category.name">
                        <div class="category-info category-box">
                            <span class="category-title">{{ category.name }}</span>
                            <div>
                                <el-button type="primary" icon="el-icon-edit" size="small"
                                           @click="onEditCategory(category)">编辑
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" size="small"
                                           @click="onDeleteCategory(category,index)">删除
                                </el-button>
                            </div>
                        </div>
                        <ul class="goods-list">
                            <li class="goods-group" v-for="goods in category.goods_list" :key="goods.id+goods.name">
                                <span class="goods-title">{{ goods.name }}</span>
                                <div class="ops-group">
                                    <span class="edit" @click="onEditGoods(goods)">编辑</span>
                                    <span class="delete" @click="onDeleteGoods(goods)">删除</span>
                                </div>
                            </li>
                            <li class="add-goods" style="font-weight:800" @click="onAddGoods(category)">+新增商品</li>
                        </ul>
                    </li>
                    <li class="category-group">
                        <div class="category-box add-category" @click="onAddCategory">+新增分类</div>
                    </li>
                </ul>
            </el-tab-pane>
        </el-tabs>

        <el-dialog title="新增/编辑分类" v-model="categoryDialogVisible">
            <el-form :model="categoryForm">
                <el-form-item label="分类名" label-width="80px">
                    <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="categoryDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSubmitCategory">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="新增/编辑商品" v-model="goodsDialogVisible" width="40%">
            <el-form :model="goodsForm" :rules="goodsRules" ref="goodsForm">
                <el-form-item label="商品名称" label-width="80px" prop="name">
                    <el-input v-model="goodsForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品图片" label-width="80px" prop="picture">
                    <el-upload
                            class="logo-upload"
                            :action="upload_action"
                            :show-file-list="false"
                            :on-success="onGoodsPictureUploadSuccess"
                            :before-upload="onBeforeUpload"
                    >
                        <img v-if="goodsForm.picture" :src="goodsForm.picture" class="logo" alt=""/>
                        <i v-else class="el-icon-plus logo-upload-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品价格" label-width="80px" prop="price">
                    <el-input v-model="goodsForm.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品介绍" label-width="80px" prop="intro">
                    <el-input v-model="goodsForm.intro" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="goodsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSubmitGoods">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>


export default {
    name: "MerchantDetail",
    data() {
        return {
            goodsForm: {
                name: '',
                picture: '',
                price: '',
                intro: '',
                category_id: '',
                id: ''
            },
            goodsRules: {
                name: [{required: true, message: "请输入商品名称！", trigger: "blur"}],
                intro: [{required: true, message: "请输入商品介绍！", trigger: "blur"}],
                picture: [{required: true, message: "请上传图片！", trigger: "blur"}],
                price: [{required: true, message: "请输入价格！", trigger: "blur"}]
            },
            categoryDialogVisible: false,
            goodsDialogVisible: false,
            categoryForm: {
                name: null,
                id: null,
                merchant_id: null
            },
            categories: [],
            upload_action: "http://127.0.0.1:8000/cms/upload",
            activeName: "1",
            merchant_id: null,
            myForm: {
                name: "",
                logo: "",
                address: "",
                notice: "",
                up_send: "0",
                lon: "",
                lat: ""
            },
            rules: {
                name: [{required: true, message: "请输入商家名称！", trigger: "blur"}],
                address: [{required: true, message: "请输入地址！", trigger: "blur"}],
                logo: [{required: true, message: "请上传图片！", trigger: "blur"}],
                lon: [{required: true, message: "请输入经度！", trigger: "blur"}],
                lat: [{required: true, message: "请输入纬度！", trigger: "blur"}]
            },
        }
    },
    methods: {
        onSubmitGoods() {
            this.$refs['goodsForm'].validate(valid => {
                if (!valid) {
                    return false
                }
                this.$flyLoading.start();
                if (this.goodsForm.id) {
                    this.$http.put(`cms/goods/${this.goodsForm.id}/`, this.goodsForm).then(res => {
                        this.$message.success('编辑商品成功')
                        this.goodsDialogVisible = false
                        for (let category of this.categories) {
                            const goods_list = category.goods_list
                            for (let index = 0; index < goods_list.length; index++) {
                                const goods = goods_list[index]
                                if (goods.id === this.goodsForm.id) {
                                    goods_list[index] = JSON.parse(JSON.stringify(this.goodsForm))
                                    this.initGoodsForm()
                                    return false
                                }
                            }
                        }
                    })
                    this.$flyLoading.end();
                } else {
                    this.$http.post(`cms/goods/`, this.goodsForm).then(res => {
                        const goods = res.data
                        for (let category of this.categories) {
                            if (category.id === goods.category) {
                                category.goods_list.push(goods)
                                break
                            }
                        }
                        this.$message.success('添加成功')
                        this.goodsDialogVisible = false
                        this.initGoodsForm()
                    });
                    this.$flyLoading.end();
                }
            })
        },
        onDeleteGoods(goods) {

            this.$messageBox.confirm("您确定要删除这个商品吗？", {
                title: "提示",
                type: "warning",
                callback: (action, instance) => {
                    if (action === 'confirm') {
                        this.$flyLoading.start();
                        // 发送删除请求
                        this.$http.delete(`cms/goods/${goods.id}/`).then(res => {
                            this.$message.success('删除成功')
                            for (let category of this.categories) {
                                const goods_list = category.goods_list
                                for (let index = 0; index < goods_list.length; index++) {
                                    const temp_goods = goods_list[index]
                                    if (temp_goods.id === goods.id) {
                                        goods_list.splice(index, 1)
                                        return false
                                    }
                                }
                            }
                        });
                        this.$flyLoading.end();
                    }
                }
            })
        },
        onEditGoods(goods) {
            this.goodsDialogVisible = true
            this.goodsForm = JSON.parse(JSON.stringify(goods))
        },
        onGoodsPictureUploadSuccess(res, file) {
            this.goodsForm.picture = res.picture
        },
        initCategoryForm() {
            this.categoryForm = {
                name: null,
                id: null,
                merchant_id: null
            }
        },
        initGoodsForm() {
            this.goodsForm = {
                name: '',
                picture: '',
                price: '',
                intro: '',
                category_id: ''
            }
        },
        onAddCategory() {
            this.initCategoryForm();
            this.categoryDialogVisible = true;
        },
        onAddGoods(category) {
            console.log(category)
            this.initCategoryForm();
            this.goodsForm.category = category.id;
            this.goodsDialogVisible = true;
        },
        onSubmitCategory() {
            if (this.categoryForm.id) {
                this.$flyLoading.start()
                this.$http.put(`cms/category/${this.categoryForm.id}/`, this.categoryForm).then(res => {

                    console.log(res);
                    this.$message.success("修改成功")
                    this.categoryDialogVisible = false

                    for (let category of this.categories) {
                        if (category.id === this.categoryForm.id) {
                            category.name = this.categoryForm.name
                            break
                        }
                    }

                    this.$flyLoading.end();
                }).catch(err => {

                    console.log(err);
                    this.$message.error("修改失败")
                    this.categoryDialogVisible = false

                    this.$flyLoading.end();
                })

            } else {
                this.categoryForm.merchant_id = this.merchant_id;
                this.$flyLoading.start();
                this.$http.post(`cms/category/`, this.categoryForm).then(res => {

                    this.$message.success('添加分类成功')
                    this.categoryDialogVisible = false
                    const category = res.data
                    console.log(res.data)
                    this.categories.push(category)
                    this.$flyLoading.end()
                }).catch(err => {
                    this.$message.error(err)
                    this.$flyLoading.end()
                })
            }
        },
        onDeleteCategory(category, index) {

            console.log(category.goods_list)

            if (category.goods_list.length > 0) {
                this.$message.info("该分类下还有商品，不能删除！")
                return false
            }
            this.$flyLoading.start()
            this.$http.delete(`cms/category/${category.id}`).then(res => {
                this.$message.success('删除成功');
                this.categories.splice(index, 1);
                this.$flyLoading.end();
            }).catch(err => {
                this.$message.error(err)
                this.$flyLoading.end();
            })
        },
        onEditCategory(category) {
            this.categoryDialogVisible = true
            this.categoryForm = {
                id: category.id,
                name: category.name,
                merchant_id: category.merchant.id
            }
        },
        onUploadSuccess(res, file) {
            console.log(res, file)
            this.myForm.logo = res.picture
        },
        onBeforeUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        onSubmit() {
            this.$refs.myForm.validate(v => {
                if (v) {
                    this.$flyLoading.start()
                    if (this.merchant_id) {
                        this.$http.put(`cms/merchant/${this.merchant_id}/`, this.myForm).then(resp => {
                            console.log(resp)
                            this.$flyLoading.end()
                            this.$message.success("编辑成功")
                            this.$router.push({name: 'merchant'})
                        }).catch(err => {
                            this.$flyLoading.end()
                            this.$message.error("编辑失败")
                        })
                    } else {
                        this.$http.post('cms/merchant/', this.myForm).then(resp => {
                            console.log(resp)
                            this.$flyLoading.end()
                            this.$message.success("添加成功")
                            this.$router.push({name: 'merchant'})
                        }).catch(err => {
                            this.$flyLoading.end()
                            this.$message.error("添加失败")
                        })
                    }
                }
            })
        },
    },
    mounted() {
        const merchant_id = this.$route.query.id;
        if (merchant_id) {
            this.merchant_id = merchant_id;
            this.$flyLoading.start();
            this.$http.get(`cms/merchant/${merchant_id}`).then(resp => {
                this.myForm = resp.data;
            }).catch(err => {
                this.$message.error("商品原信息获取失败！");

            })

            this.$http.get(`cms/category/merchant/${merchant_id}`).then(resp => {
                this.categories = resp.data;
                this.$flyLoading.end();
            }).catch(err => {
                console.log(err);
                this.$flyLoading.end();
            })
        }

    },
    watch: {
        categories: {
            deep: true,
            handler: function (newValue) {
            }
        }
    }
}
</script>

<style scoped lang='scss'>
.form-group {
  padding-top: 20px;
  width: 460px;
}

.logo-upload {
  .logo {
    width: 178px;
    height: 133px;
    display: block;
  }

  .logo-upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 133px;
    line-height: 133px;
    text-align: center;
  }
}

.category-list {
  width: 800px;

  .category-group {
    .category-box {
      padding: 10px;
      box-sizing: border-box;
    }

    .add-category {
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }

    .category-info {
      background-color: rgb(217, 236, 255);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .goods-list {
      .goods-group {
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        padding: 10px;
        margin: 10px 0;
        background-color: #ddd;

        &:hover {
          background-color: #ccc;
        }

        &:hover .ops-group {
          display: block;
        }

        .ops-group {
          display: none;
          font-size: 12px;
          justify-content: space-between;

          span {
            cursor: pointer;
          }

          .edit {
            margin-right: 10px;
          }
        }
      }

      .add-goods {
        background-color: #ddd;
        text-align: center;
        padding: 10px;
        cursor: pointer;
        margin-bottom: 20px;
      }
    }
  }
}
</style>

<style scoped>
.logo-upload >>> .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.logo-upload >>> .el-upload:hover {
    border-color: #409eff;
}
</style>
